/**
 * 
 */
package org.t2.game.server.module.recharge.service;

import java.util.ArrayList;
import java.util.List;

import org.gaming.prefab.thing.NoticeType;
import org.gaming.service.service.jvm.PlayerOneToOneResetableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.t2.design.module.AllRechargeTable;
import org.t2.design.module.autogen.AllRechargeAbstractTable.AllRechargeCfg;
import org.t2.game.server.module.mail.constant.MailText;
import org.t2.game.server.module.mail.model.Mail;
import org.t2.game.server.module.mail.service.MailService;
import org.t2.game.server.module.recharge.model.RechargePlayer;
import org.t2.game.server.module.tips.GameCause;

/**
 * @author YY
 */
@Service
public class RechargePlayerService extends PlayerOneToOneResetableService<RechargePlayer> {

	@Autowired
	private MailService mailService;
	
	@Override
	protected RechargePlayer createWhenNull(long entityId) {
		return new RechargePlayer();
	}

	@Override
	protected void doDailyReset(RechargePlayer entity) {
		entity.setDailyRecharge(0);
		entity.getDailyRewards().clear();
	}
	
	public void onRecharge(long playerId, long money) {
		RechargePlayer entity = this.getEntity(playerId);
		
		entity.setDailyRecharge(entity.getDailyRecharge() + money);
		entity.setHisRecharge(entity.getHisRecharge() + money);
		
		List<Mail> mails = new ArrayList<>();
		
		List<AllRechargeCfg> dailyCfgs = AllRechargeTable.ins().getInTypeCollector(1);
		long dailyRecharge = entity.getDailyRecharge() / 100;
		for(AllRechargeCfg dailyCfg : dailyCfgs) {
			if(dailyCfg.getRechargeNum() > dailyRecharge) {
				break;
			}
			if(entity.getDailyRewards().contains(dailyCfg.getId())) {
				continue;
			}
			String content = String.format(MailText.Mail1001Content, dailyCfg.getRechargeNum());
			Mail mail = mailService.newMail(playerId, MailText.Mail1001Title, content, dailyCfg.getReward(), GameCause.RECHARGE);
			mails.add(mail);
			
			entity.getDailyRewards().add(dailyCfg.getId());
		}
		List<AllRechargeCfg> hisCfgs = AllRechargeTable.ins().getInTypeCollector(2);
		long hisRecharge = entity.getHisRecharge() / 100;
		for(AllRechargeCfg hisCfg : hisCfgs) {
			if(hisCfg.getRechargeNum() > hisRecharge) {
				break;
			}
			if(entity.getHisRewards().contains(hisCfg.getId())) {
				continue;
			}
			String content = String.format(MailText.Mail1002Content, hisCfg.getRechargeNum());
			Mail mail = mailService.newMail(playerId, MailText.Mail1002Title, content, hisCfg.getReward(), GameCause.RECHARGE);
			mails.add(mail);
			
			entity.getHisRewards().add(hisCfg.getId());
		}
		if(mails.isEmpty()) {
			return;
		}
		this.update(entity);
		mailService.sendMail(mails, NoticeType.NORMAL);
	}
}
